package cn.lz.socket.handler;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;


/**
 * socket服务器端处理类
 * @author: TT
 * @date: 2018/12/22
 * @time: 11:00
 * @version: V1.0
 */
public class ServerHandler extends IoHandlerAdapter {

	Logger logger = LoggerFactory.getLogger(ServerHandler.class);
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("出现异常 :" + session.getRemoteAddress().toString() + " : " + cause.toString());

		session.write("出现异常");
		session.closeNow();
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("连接创建 : " + session.getRemoteAddress().toString());
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("连接打开: " + session.getRemoteAddress().toString());
	}



	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.info("接受到数据 :" + String.valueOf(message));

        IoBuffer bbuf = (IoBuffer) message;
        byte[] byten = new byte[bbuf.limit()];
        bbuf.get(byten, bbuf.position(), bbuf.limit());
        System.out.println("收到消息：" );
        byte[] bts = new byte[10];
        for(int i=0;i<10;i++){
            bts[i] = (byte)i;
        }
        IoBuffer buffer = IoBuffer.allocate(10);
        buffer.put(bts);
        buffer.flip();
        session.write(buffer);


//        String text = String.valueOf(message);
//		logger.info("开始分析数据 ");
//		String result = analyzeData(text, session);
//		session.write(result);

	}

	private String analyzeData(String text, IoSession session) throws InterruptedException, ExecutionException {

		String responseMessage = "接受到数据";
		return responseMessage;
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.info("返回消息内容 : " + message.toString());
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		if (status == IdleStatus.READER_IDLE) {
			logger.info("进入读空闲状态");
			session.closeNow();
		} else if (status == IdleStatus.BOTH_IDLE) {
			logger.info("BOTH空闲");
			session.closeNow();
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("连接关闭 : " + session.getRemoteAddress().toString());
		int size = session.getService().getManagedSessions().values().size();
		logger.info("连接关闭时session数量==》" + size);
	}

}